import BackBtn from '@components/globalComponents/BackBtn';
import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';

function HuluBaby3D(): React.ReactElement {
  const mountRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!mountRef.current) return;

    const currentMount = mountRef.current;

    // 创建场景
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xeeeeee);

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      75,
      currentMount.clientWidth / currentMount.clientHeight,
      0.1,
      1000,
    );
    camera.position.set(0, 0, 5);

    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(currentMount.clientWidth, currentMount.clientHeight);
    currentMount.appendChild(renderer.domElement);

    // 添加环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 1);
    scene.add(ambientLight);

    // 添加方向光
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(1, 1, 1);
    scene.add(directionalLight);

    // 3. 加载纹理图片（shaded_00.png）
    const textureLoader = new THREE.TextureLoader();
    const baseTexture = textureLoader.load(
      'http://127.0.0.1:9981/hulu-obj-data/color-obj/shaded_00.png',
      (texture) => {
        // 纹理加载完成后触发（可选，用于调试）

        texture.needsUpdate = true; // 强制更新纹理
      },
      undefined,
      (error) => {
        // eslint-disable-next-line no-console
        console.error('纹理加载失败：', error); // 加载失败提示
      },
    );

    // 加载 OBJ 模型
    const loader = new OBJLoader();
    loader.load(
      // 假设 base.obj 文件放在 public 目录下
      'http://127.0.0.1:9981/hulu-obj-data/base.obj',
      (object) => {
        // 可选：给模型添加材质
        object.traverse((child) => {
          // THREE.Mesh是three.js中用于表示3D模型的基本元素，它包含了模型的几何信息和材质信息。
          if ((child as THREE.Mesh).isMesh) {
            (child as THREE.Mesh).material = new THREE.MeshStandardMaterial({
              // 主体的颜色 浅蓝色
              color: 0xadd8e6, // 0xadd8e6 是浅蓝色的十六进制颜色值
              metalness: 0.3, // 金属度 0-1 之间的浮点数，0 表示非金属，1 表示金属
              roughness: 0.5, // 粗糙度 0-1 之间的浮点数，0 表示平滑，1 表示粗糙
              map: baseTexture,
            });
          }
        });

        // 调整模型大小和位置
        const box = new THREE.Box3().setFromObject(object);
        const center = box.getCenter(new THREE.Vector3());
        object.position.sub(center); // 居中模型
        const size = box.getSize(new THREE.Vector3());
        const maxDim = Math.max(size.x, size.y, size.z);
        const scale = 2 / maxDim;
        object.scale.set(scale, scale, scale);

        scene.add(object);
      },
      (xhr) => {
        console.log(`${(xhr.loaded / xhr.total) * 100}% loaded`);
      },
      (error) => {
        console.error('加载 OBJ 文件失败:', error);
      },
    );

    // 鼠标控制（简单旋转）
    let mouseX = 0;
    let mouseY = 0;
    const onMouseMove = (event: MouseEvent) => {
      mouseX = (event.clientX / window.innerWidth) * 2 - 1;
      mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
    };
    window.addEventListener('mousemove', onMouseMove);

    // 动画循环
    const animate = () => {
      requestAnimationFrame(animate);

      // 根据鼠标位置旋转场景
      scene.rotation.y = mouseX * 0.5;
      scene.rotation.x = mouseY * 0.2;

      renderer.render(scene, camera);
    };
    animate();

    // 处理窗口大小变化
    const handleResize = () => {
      camera.aspect = currentMount.clientWidth / currentMount.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(currentMount.clientWidth, currentMount.clientHeight);
    };
    window.addEventListener('resize', handleResize);

    // 清理函数
    return () => {
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('resize', handleResize);
      currentMount.removeChild(renderer.domElement);
      return;
      renderer.dispose();
    };
  }, []);

  return (
    <div>
      {/* 返回首页按钮 */}
      <div
        style={{ position: 'absolute', top: '16px', left: '16px', zIndex: 10 }}
      >
        <BackBtn />
      </div>
      <div ref={mountRef} style={{ width: '100%', height: '100vh' }} />
    </div>
  );
}

export default HuluBaby3D;
